﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using GodProject.peoples;

namespace WebGodServer.Database
{
  class DatabaseFiller
  {
    DataContext db;
    public DatabaseFiller(string connectionString)
    {
      db = new DataContext(connectionString);
    }

    public void InsertPair(Human firstHuman, Human secondHuman)
    {
      Parent parent = firstHuman as Parent;
      Student student = secondHuman as Student;
      if (parent == null && student == null)
      {
        parent = secondHuman as Parent;
        student = firstHuman as Student;
      }

      long parentId = InsertParentToDB(parent);
      long studentId = InsertStudentToDB(student);
      InsertPairToDB(parentId, studentId);
    }

    private void InsertPairToDB(long parentId, long studentId)
    {
      DBPair pairRecord = new DBPair();
      pairRecord.Parent_id = parentId;
      pairRecord.Student_id = studentId;

      Table<DBPair> pairTable = db.GetTable<DBPair>();
      pairTable.InsertOnSubmit(pairRecord);
      db.SubmitChanges();
    }

    private long InsertParentToDB(Parent parent)
    {
      DBParent parentRecord = new DBParent();
      parentRecord.Name = parent.Name;
      parentRecord.Age = parent.Age;
      parentRecord.Child_count = parent.ChildCount;
      parentRecord.Sex = parent.Sex == Sex.Male;
      if(parent is CoolParent)
      {
        parentRecord.Money_count = (parent as CoolParent).Money;
      }

      Table<DBParent> parentTable = db.GetTable<DBParent>();
      parentTable.InsertOnSubmit(parentRecord);
      db.SubmitChanges();
      return parentRecord.Id;
    }

    private long InsertStudentToDB(Student student)
    {
      DBStudent studentRecord = new DBStudent();
      studentRecord.Name = student.Name;
      studentRecord.Age = student.Age;
      studentRecord.Surname = student.Middlename;
      studentRecord.Sex = student.Sex == Sex.Male;
      if (student is Botan)
      {
        studentRecord.Avg_mark = (student as Botan).AverageMark;
      }

      Table<DBStudent> studentTable = db.GetTable<DBStudent>();
      studentTable.InsertOnSubmit(studentRecord);
      db.SubmitChanges();
      return studentRecord.Id;
    }

  }
}
